<template>
	<view :class="['container',$store.state.theme.themeType]"
		:style="{'--color1':$store.state.theme.color1,'--color2':$store.state.theme.color2,'padding-top': 'var(--status-bar-height)','--nav_color':$store.state.theme.navColor,'--background':$store.state.theme.background}">
		<view class="top-search">
			<uni-icons type="left" class="back" size="24" @click="back()"></uni-icons>
			<search v-model="keyword" @change="e=>{keyword=e}" @confirm="asyncSearch('suffix')"></search>
		</view>
		<view :class="['loading',showLoading?'show':'']">
			<image style="height: 100rpx;width: 100rpx;" src="../../static/loading1.gif"></image>
		</view>
		<view style="height: 40rpx;font-size: 26rpx;padding-left: 40rpx;">
			共找到{{List.length}}本小说
		</view>
		<scroll-view @scroll="scroll"
			:style="{'height':scroll_height+'px !important','--topFill':topBlankFill+'px','--bottomFill':bottomBlankFill+'px'}"
			:scroll-y="true">
			<!-- <transition-group name="flip-list" tag="uni-view"> -->
			<view style="height: 26rpx;font-size: 26rpx;padding-left: 40rpx;" class="" v-if="List.length">

			</view>
			<block v-for="i,index in showDataList" :key="index">
				<view class="item" v-if="i" @click="jump(i)">
					<view class="left">
						<image class="cover" src="../../static/cover.jpeg" mode="aspectFit"></image>
						<!-- <image class="cover" v-if="!i.is_load" src="../../static/82620s.jpg" mode="aspectFit"></image> -->
					</view>
					<view class="right">
						<view class="name">
							{{i.name}}
						</view>
						<view class="author">
							{{i.author}}
						</view>
						<view class="surplus">
							{{i.sources.length}}
						</view>
					</view>
				</view>
			</block>

			<!-- </transition-group> -->

			<view v-if="List.length==0" :style="{'height':scroll_height+'px !important'}" class="empty">
				<image src="../../static/empty.png" mode=""></image>
			</view>

		</scroll-view>
	</view>
</template>

<script>
	import search from '../../components/search.vue'
	import request2 from "../../utils/request2.js"
	import request from "../../utils/request.js"
	import {
		getWebsiteList
	} from '../../api/index.js'
	import {
		addError
	} from "../../api/system.js"
	import {
		RpxToPx,
		PxToRpx
	} from "../../utils/index.js"
	export default {
		components: {
			search
		},
		computed: {
			endIndex() {
				let end = this.startIndex + this.containSize
				if (end > this.List.length && this.List.length != 0) {
					this.startIndex = this.List.length - 1 - this.containSize
					this.startIndex = this.startIndex < 0 ? 0 : this.startIndex
					return this.List.length - 1
				}
				return end
			},
			showDataList() {
				return this.List.slice(this.startIndex, this.endIndex + 1)
			},
			topBlankFill() {
				return this.startIndex * this.RpxToPx(240)
			},
			bottomBlankFill() {
				return (this.List.length - this.endIndex) * this.RpxToPx(240)
			}
		},
		data() {
			return {
				keyword: null,
				List: [],
				websiteList: [],
				startIndex: 0,
				containSize: 0,
				showLoading: false
			};
		},
		onLoad(e) {
			this.scroll_height = getApp().globalData.screenHeight - 36 - (2 * parseInt(this.RpxToPx(40))) - getApp()
				.globalData
				.statusBarHeight
			this.containSize = ~~(this.scroll_height / this.RpxToPx(240)) + 2
			this.keyword = e.keyword

			if (this.websiteList.length == 0) {
				uni.showLoading({
					title: "获取书源中...",
					mask: true
				})
				this.$store.dispatch('data/getWebsiteList').then(res => {
					this.websiteList = res
					uni.hideLoading()
					this.asyncSearch()
				})
				return
			}
			this.websiteList = this.$store.state.data.websiteList
			this.asyncSearch()
			uni.hideLoading()
		},
		onShow() {

			//#ifdef APP
			plus.navigator.setStatusBarStyle(this.$store.state.theme.themeType == 'dark' ? 'light' : 'dark');
			//#endif

		},
		onReady() {
			//#ifdef APP
			plus.navigator.setStatusBarStyle(this.$store.state.theme.themeType == 'dark' ? 'light' : 'dark');
			//#endif
		},
		onUnload() {
			this.time = new Date().getTime()
		},
		methods: {
			scroll(e) {
				if (~~(e.detail.scrollTop / this.RpxToPx(240)) + this.containSize >= this.List.length) return
				this.startIndex = ~~(e.detail.scrollTop / this.RpxToPx(240))
			},
			back() {
				uni.navigateBack()
			},
			asyncSearch() {
				if (!this.keyword) {
					uni.showToast({
						icon: 'none',
						title: "搜索关键词不能为空"
					})
					return
				}
				this.showLoading = true
				let index = 0
				this.List = []
				let that = this
				let tasks = this.websiteList.map((i, j) => {
					return {
						func: this.work,
						num: j
					}
				})
				this.time = new Date().getTime()
				let time = this.time
				uni.showLoading({
					mask: true
				})
				Promise.all(Array.from({
					length: 8
				}).map((i, j) => {
					return new Promise((resolve, reject) => {
						function run() {
							if (tasks.length <= 0) {
								resolve()
								return
							}
							let task = tasks.shift()
							if (time != that.time) reject()
							task.func(task.num, that.time).then(res => {
								if (time != that.time) reject()
								if (res.length != 0) uni.hideLoading()
								for (let o of res) {
									let names = that.List.map(i => i.name + '_' + i.author)
									if (names.indexOf(o.name + '_' + o.author) > -1) {
										let n_index = names.indexOf(o.name + '_' + o.author)
										let sourceList = that.List[n_index].sources.map(i => i
											.id)
										if (sourceList.indexOf(o.sources[0].id) == -1) that
											.List[n_index].sources.push(o.sources[0])
									} else {
										that.List.push(o)
									}
								}
								that.List.sort(function(a, b) {
									return b.sources.length - a.sources.length
								})
								run()
							}).catch(_ => {
								run()
							})
						}
						run()
					})
				})).then(_ => {
					uni.hideLoading()
					this.showLoading = false
					if (that.List.length == 0) {
						uni.showToast({
							icon: 'none',
							title: "没找到相关小说"
						})
						return
					}
					uni.showToast({
						icon: "none",
						title: "搜索完成"
					})
				}).catch(_ => {
					console.log('中断');
				})
			},
			work(index, time) {
				if (!this.websiteList[index].search_url|| this.time != time) {
					return new Promise(resolve => {
						resolve([])
					})
				}
				let list_content_zz = this.websiteList[index].list_content_zz
				let item_zz = this.websiteList[index].item_zz
				let search_url = this.websiteList[index].search_url
				let method = this.websiteList[index].method
				let header = this.websiteList[index].header
				let key = this.websiteList[index].search_key
				let search_form = this.websiteList[index].search_form
				let charset = this.websiteList[index].charset
				let data = JSON.parse(JSON.stringify(search_form))
				data[key] = this.keyword
				let a = {
					name: '链接',
					num: item_zz.indexOf('[链接]')
				}
				let b = {
					name: '名称',
					num: item_zz.indexOf('[名称]')
				}
				let c = {
					name: '作者',
					num: item_zz.indexOf('[作者]')
				}
				item_zz = item_zz.replace('[链接]', '(.*?)').replace('[名称]', '(.*?)').replace('[作者]', '(.*?)')
				let d = [a, b, c]
				let e = {}
				d.sort(function(i, j) {
					return i.num > j.num
				})
				for (let i = 0; i < d.length; i++) {
					e[d[i].name] = i
				}

				return new Promise(resolve => {
					request2(search_url, method, data, "", header,charset).then(res => {
						let r = new RegExp(list_content_zz, 'gs')
						let list_content = res.match(r)[0]
						r = new RegExp(item_zz, 'gs')
						let list = list_content.matchAll(r)
						let novels = []
						for (let s of list) {
							let source = JSON.parse(JSON.stringify(this.websiteList[index]))
							let url = s[e['链接'] + 1]
							if (url.indexOf(this.websiteList[index].host) > -1) {
								//包含host
								url = s[e['链接'] + 1]
							} else {
								//不包含host
								url = s[e['链接'] + 1]
								if (url[0].charCodeAt() == 47) {
									url = this.websiteList[index].host + url
								} else {
									let next_host = /.*\//g.exec(this.websiteList[index].url)[0]
									url = next_host + url
								}
							}
							if (this.websiteList[index].host.indexOf('https://') > -1 && url.indexOf(
									'https://') == -1) {
								url = url.replace('http://', 'https://')
							} else if (this.websiteList[index].host.indexOf('http://') > -1 && url
								.indexOf('http://') == -1) {
								url = o.url.replace('http://', 'https://')
							}
							source.url = url.replace(/\n*/g, '').replace(/ /g, '')
							let o = {
								'name': s[e['名称'] + 1].replace(/\n*/g, '').replace(/ /g, '')
									.replace(/<.*?>/g, ''),
								'author': s[e['作者'] + 1].replace(/\n*/g, '').replace(/ /g, '')
									.replace(/<.*?>/g, ''),
								'sources': [source]
							}
							novels.push(o)
						}
						if (this.time != time) {
							resolve([])
						} else {
							resolve(novels)
						}

					}).catch(e => {
						console.log(e);
						resolve([])
					})
				})
			},
			load(i) {
				this.$set(i, 'is_load', true)
			},

			jump(i) {
				let info = JSON.parse(JSON.stringify(i))
				delete info.is_load
				uni.setStorageSync('info', info)
				uni.navigateTo({
					url: "../detail/detail"
				})
			},
			PxToRpx(num) {
				return PxToRpx(num)
			},
			RpxToPx(num) {
				return RpxToPx(num)
			}
		}
	}
</script>

<style lang="less">
	.container.dark {
		color: var(--color-main);

		/deep/ .uni-searchbar__box {
			background-color: rgb(24, 24, 24) !important;
		}

		/deep/.uni-searchbar__cancel {
			color: white;
		}

		/deep/.uni-input-input {
			color: white !important;
		}

		/deep/.uni-icons {
			color: white !important;
		}

		/deep/.uni-input-placeholder {
			color: white !important;
		}
	}

	.container {

		background: var(--background);

		.show.loading {
			transform: translate(0, 0);
		}

		.loading {
			position: absolute;
			z-index: 99;
			right: 0;
			transition: all .4s ease;
			transform: translate(100px, 0);
		}

		.back {
			padding: 5px;
			border-radius: 99px;
			display: flex;
			justify-content: center;
			align-items: center;
			background: var(--background) !important;
			box-shadow: 10rpx 10rpx 15rpx var(--color1),
				-10rpx -10rpx 15rpx var(--color2);
			margin-left: 10px;
		}

		/deep/ .uni-scroll-view-content {
			padding-top: var(--topFill) !important;
			padding-bottom: var(--bottomFill) !important;
		}

		.top-search {
			display: flex;
			align-items: center;
		}

		.empty {
			display: flex;
			align-items: center;
			justify-content: center;
		}

		/deep/ .uni-easyinput {
			padding: 20rpx;
			box-sizing: border-box;
			color: black !important;
		}

		/deep/.uni-easyinput__content {
			background: var(--nav_color);
			border: none;
		}

		/deep/.uni-icons {
			color: black !important;
		}

		/deep/.uni-input-input {
			color: black !important;
		}

		.item {
			position: relative;
			display: flex;
			margin: 40rpx 40rpx;
			padding: 10rpx;
			border-radius: 10rpx;
			background: var(--background);
			box-shadow: 10rpx 10rpx 15rpx var(--color1),
				-10rpx -10rpx 15rpx var(--color2);
			height: 200rpx;

			.left {
				width: 150rpx;

				/deep/div {
					background-size: 100% 100% !important;
				}

				.none {
					display: none;
				}

				.cover {
					position: absolute;
					height: 200rpx;
					width: 150rpx;
					box-sizing: border-box;
					border-radius: 10rpx;

				}
			}

			.right {
				padding-left: 30rpx;
				flex: 1;

				.surplus {
					position: absolute;

					background-color: var(--background) !important;
					box-shadow: 10rpx 10rpx 15rpx var(--color1),
						-10rpx -10rpx 15rpx var(--color2);
					color: var(--color-main);
					right: 10rpx;
					bottom: 10rpx;
					font-size: 24rpx;
					height: 40rpx;
					padding: 5rpx 20rpx;
					line-height: 40rpx;
					border-radius: 9999px;
					text-align: center;

				}

				.name {
					width: 440rpx;
					font-size: 32rpx;
					font-weight: bolder;
					padding: 20rpx 0;
					overflow: hidden;
					white-space: nowrap;
					text-overflow: ellipsis;
				}

				.author {
					font-size: 24rpx;
				}
			}
		}
	}
</style>
